<?php

class PostTagModel extends Model {
	
	
    public function index(){
		return 1;
    }
    
	//由tagId获取PostIds数组
    function getPostIds($tagId, $limit = 15) {
    	$condition = array('tag_id'=>$tagId);
    	$postIds = $this->where($condition)->limit($limit)->getField('id,post_id');
    	return $postIds;
    }
    
    //由postId获取tagIds数组
    function getTagIds($postId) {
    	$condition = array('post_id'=>$postId);
    	$tagIds = $this->where($condition)->getField('id,tag_id');
    	return $tagIds;
    }

    /**
     * 获取标签
     * @param int $postIds
     * @return array('tagId'=>'tagName');
     */
    function getTags($postIds) {
    	$tags = array();
    	static $Tag;
    	if(!isset($Tag)) {
    		$Tag = D('Tag');
    	}
    	$isOne = false;
    	if(!is_array($postIds)) {
    		$postIds = array($postIds);
    		$isOne = true;
    	}
    	foreach($postIds as $postId) {
    		$tagIdArr = $this->getTagIds($postId);
    		if($tagIdArr) {
    			foreach($tagIdArr as $tagid) {
    				$tags[$postId][$tagid] = $Tag->getOne($tagid);
    			}
    		}
    	}
    	
    	if($isOne) {
    		$tags = $tags[$postIds[0]];
    	}
    	
    	return $tags;
    }
    
    //添加post和tag对应关系
    function addPostTag($postId, $tagId) {
    	$data = array(
    		'post_id'=>$postId,
    		'tag_id'=>$tagId
    	);
    	$id = $this->add($data);
    	return $id;
    }
    
    
    //删除By postId
    function delByPostId($postId) {
    	$condition = array('post_id'=>$postId);
    	$tagArr = $this->where($condition)->select();
    	foreach($tagArr as $tag) {
	    	$haveTag = $this->field('id,count')->where($con)->find();
	    	$data = array();
	    	$data['id'] = $haveTag['id'];
	    	$data['count'] = $haveTag['count'] + 1;
	    	$this->save($data);
    	}
    	$result = $this->where($condition)->delete();
    	return $result;
    }
    
    //删除By tagId
    function delByTagId($tagId) {
    	$condition = array('tag_id'=>$tagId);
    	$result = $this->where($condition)->delete();
    	return $result;
    }
    
}